﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Intorise.Common;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Web;
using System.Threading;
using System.Net.Sockets;

namespace Model
{
    public class GmBotEngine : BotEngine
    {
        public GmBotEngine(Player player) : base(player) { }

        public override bool Login()
        {
            string loginUrl = "http://www.gm99.com/login/login2/";
            string checkCodeUrl = "https://cas.sdo.com/authen/checkCodeLogin.jsonp?callback=checkCodeLogin_JSONPMethod&guid={0}&password={1}&appId=10&areaId=1&serviceUrl=http%3A%2F%2Favd.qidian.com%2FOALoginJump.aspx%3FReturnUrl%3Dhttp%253a%252f%252fgame.qidian.com%252fgame%252fdtszj%252flogin.aspx%26sitetype%3D9999&productVersion=v5&frameType=3&locale=zh_CN&version=21&tag=20&authenSource=2&productId=2&_={2}";
            string enterGameUrl = "http://www.gm99.com/play_games/play/server/mu/id/";
            string registerUrl = "http://apidts.gm99.com/client/?user_name={0}&server_id=S{1}&is_adult=-1&time={2}&sign=dc4af81336e641eb9de7183d89588271&client=1";
            string registerServerUrl = null;

            CookieContainer cookies = new CookieContainer();
            ConsoleBLL.WriteLine(player + " 开始登录...");
            var request = net.SendRequest("http://www.gm99.com/mu/", "GET", cookies);
            var response = (HttpWebResponse)request.GetResponse();
            var html = net.GetResponseHtml(response);
            request = net.SendRequest(loginUrl, "POST", cookies);
            net.PostData("uname=" + player.AccountName + "&password=" + player.PlayerAccount.Password + "&forward=%2Fmu%2F", request);
            response = (HttpWebResponse)request.GetResponse();
            html = net.GetResponseHtml(response);

            html = html.Replace("staticLogin_JSONPMethod(", "").Replace(")", "");
            JObject result = (JObject)JsonConvert.DeserializeObject(html);
            if (infoLog)
            {
                ConsoleBLL.WriteLineInfo(player + " login result:" + result);
            }
            var flag = result["result"].ToString();
            switch (flag)
            {
                case "1":
                    ConsoleBLL.WriteLineError(player + " 用户名密码正确，登录成功，进入游戏...");
                    break;
                default:
                    ConsoleBLL.WriteLineError(player + " 登录失败，账户密码错误");
                    ConsoleBLL.WriteLine(html.ToString());
                    this.player.Status = PlayerStatusEnum.账户密码错误;
                    return false;
            }

            request = net.SendRequest(enterGameUrl + player.ServerID, "GET", cookies);
            html = net.GetResponseHtml(request);

            //获取登录游戏服务器的地址


            var url = Tools.SubString(html, "<iframe src=\"", "\" name=\"playFrame\"", true);
            request = net.SendRequest(url, "GET", cookies);
            html = net.GetResponseHtmlGzip(request);

            if (infoLog)
            {
                ConsoleBLL.WriteLineInfo(player + " login enterGameUrl:" + request.RequestUri);
            }

            port = GameHelper.GetPort(html);
            if (port == 0)
            {
                ConsoleBLL.WriteLineError(player + " 无法获取服务器端口，html:");
                ConsoleBLL.WriteLine(html);
                return false;
            }
            head = new byte[] { 0x00, 0x01, 0x87, 0x70 };
            serverNo = Tools.GetAscII(player.PlayerAccount.ServerID);
            accountData = Tools.GetAscII(Tools.SubString(url, "user_name=", "&", true));
            time = Tools.GetAscII(GameHelper.GetTime(html));
            singn = Tools.GetAscII(GameHelper.GetSign(html));
            ip = GameHelper.GetIP(html);

            return true;
        }

        public override bool EnterGameServer()
        {
            DateTime startTime = DateTime.Now;
            Client = new TcpClient(ip, 843);
            var data = Tools.GetAscII("<policy-file-request/>\0");
            net.SendData(Client, data);
            Client.Close();

            Client = new TcpClient(ip, port);
            Begin();

            data = Tools.Contact(head, DataPackager.GetNetworkData((short)serverNo.Length), serverNo, net.GetNetworkBytes((short)accountData.Length), accountData, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A }
                , time, new byte[] { 0x00, 0x01, 0x31, 0x00, 0x20 }, singn
                , new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x35, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x75, 0x6E, 0x64, 0x65, 0x66, 0x69, 0x6E, 0x65, 0x64, 0x00, 0x00 });
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            net.SendData(Client, data, data.Length);

            while (!player.Entered)
            {
                Thread.Sleep(500);
                if (player.Config.TimeoutLogin < (DateTime.Now - startTime).TotalSeconds) { break; }
            }

            if (!player.Entered)
            {
                ConsoleBLL.WriteLineWaring(player + " 进入游戏超时！");
                Stop();
            }
            return player.Entered;
        }
    }
}
